package com.tyut.listener;

import com.tyut.domain.MusicDocument;
import com.tyut.service.SearchService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 音乐索引监听器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MusicIndexListener {

    private final SearchService searchService;

    /**
     * 监听音乐创建/更新消息
     *
     * @param document 音乐文档
     */
    @RabbitListener(queues = "music.index.queue")
    public void handleMusicIndex(MusicDocument document) {
        log.info("收到音乐索引消息: {}", document);
        
        // 处理标签数组
        if (document.getTags() != null && !document.getTags().isEmpty()) {
            List<String> tagArray = Arrays.stream(document.getTags().split(","))
                    .map(String::trim)
                    .filter(tag -> !tag.isEmpty())
                    .collect(Collectors.toList());
            document.setTagArray(tagArray);
        }
        
        boolean result = searchService.indexMusic(document);
        log.info("音乐索引结果: {}", result);
    }

    /**
     * 监听音乐删除消息
     *
     * @param id 音乐ID
     */
    @RabbitListener(queues = "music.delete.queue")
    public void handleMusicDelete(String id) {
        log.info("收到音乐删除消息: {}", id);
        boolean result = searchService.deleteMusic(id);
        log.info("音乐删除结果: {}", result);
    }
} 